<template>
  <div class="learning-community">
    <div class="community-header">
      <h2>学习社区</h2>
      <p>分享经验，交流学习，共同进步</p>
      <el-button type="primary" @click="showPostDialog">
        <el-icon><Edit /></el-icon>
        发布新帖子
      </el-button>
    </div>

    <!-- 社区内容区 -->
    <div class="community-content">
      <!-- 筛选和搜索 -->
      <div class="filter-section">
        <el-input
          v-model="searchQuery"
          placeholder="搜索帖子..."
          class="search-input"
          clearable
          @clear="handleSearch"
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        
        <el-select v-model="selectedCategory" placeholder="帖子分类" @change="handleCategoryChange">
          <el-option label="全部" value="" />
          <el-option label="学习经验" value="experience" />
          <el-option label="技术讨论" value="discussion" />
          <el-option label="问题求助" value="help" />
          <el-option label="资源分享" value="resource" />
        </el-select>
        
        <el-select v-model="sortBy" placeholder="排序方式" @change="handleSortChange">
          <el-option label="最新发布" value="latest" />
          <el-option label="最多评论" value="most_comments" />
          <el-option label="最多点赞" value="most_likes" />
        </el-select>
      </div>

      <!-- 帖子列表 -->
      <div class="posts-list">
        <el-card v-for="post in filteredPosts" :key="post.id" class="post-card">
          <div class="post-header">
            <div class="post-author">
              <el-avatar :src="post.author.avatar" />
              <div class="author-info">
                <span class="author-name">{{ post.author.name }}</span>
                <span class="post-time">{{ post.createTime }}</span>
              </div>
            </div>
            <el-tag :type="getCategoryTag(post.category)">{{ post.category }}</el-tag>
          </div>
          
          <div class="post-content" @click="viewPostDetail(post)">
            <h3 class="post-title">{{ post.title }}</h3>
            <p class="post-summary">{{ post.summary }}</p>
            <div class="post-tags">
              <el-tag
                v-for="tag in post.tags"
                :key="tag"
                size="small"
                effect="plain"
                class="post-tag"
              >
                {{ tag }}
              </el-tag>
            </div>
          </div>
          
          <div class="post-footer">
            <div class="post-stats">
              <span><el-icon><View /></el-icon> {{ post.views }}</span>
              <span><el-icon><ChatLineRound /></el-icon> {{ post.comments }}</span>
              <span><el-icon><Star /></el-icon> {{ post.likes }}</span>
            </div>
            <div class="post-actions">
              <el-button text @click="likePost(post)">
                <el-icon><Star /></el-icon>
                点赞
              </el-button>
              <el-button text @click="viewPostDetail(post)">
                <el-icon><ChatLineRound /></el-icon>
                评论
              </el-button>
              <el-button text @click="sharePost(post)">
                <el-icon><Share /></el-icon>
                分享
              </el-button>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 分页 -->
      <div class="pagination-section">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="totalPosts"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 发帖对话框 -->
    <el-dialog
      v-model="postDialogVisible"
      title="发布新帖子"
      width="60%"
    >
      <el-form :model="newPost" :rules="postRules" ref="postFormRef">
        <el-form-item label="标题" prop="title">
          <el-input v-model="newPost.title" placeholder="请输入帖子标题" />
        </el-form-item>
        
        <el-form-item label="分类" prop="category">
          <el-select v-model="newPost.category" placeholder="请选择帖子分类">
            <el-option label="学习经验" value="experience" />
            <el-option label="技术讨论" value="discussion" />
            <el-option label="问题求助" value="help" />
            <el-option label="资源分享" value="resource" />
            <el-option label="面试经验" value="interview" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="面试时间" v-if="newPost.category === 'interview'">
          <el-date-picker
            v-model="newPost.interviewTime"
            type="datetime"
            placeholder="选择面试时间"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm"
          />
        </el-form-item>

        <el-form-item label="AI出题" v-if="newPost.category === 'interview'">
          <el-switch v-model="newPost.enableAIQuestion" />
          <span class="ai-hint" v-if="newPost.enableAIQuestion">启用AI智能出题和评分</span>
        </el-form-item>
        
        <el-form-item label="内容" prop="content">
          <el-input
            v-model="newPost.content"
            type="textarea"
            :rows="10"
            placeholder="请输入帖子内容"
          />
        </el-form-item>
        
        <el-form-item label="标签">
          <el-select
            v-model="newPost.tags"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="请选择或输入标签"
          >
            <el-option
              v-for="tag in commonTags"
              :key="tag"
              :label="tag"
              :value="tag"
            />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="postDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitPost">发布</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 帖子详情对话框 -->
    <el-dialog
      v-model="postDetailVisible"
      :title="selectedPost?.title"
      width="70%"
    >
      <div v-if="selectedPost" class="post-detail">
        <div class="detail-header">
          <div class="author-info">
            <el-avatar :src="selectedPost.author.avatar" />
            <div class="author-meta">
              <span class="author-name">{{ selectedPost.author.name }}</span>
              <span class="post-time">{{ selectedPost.createTime }}</span>
            </div>
          </div>
          <el-tag :type="getCategoryTag(selectedPost.category)">
            {{ selectedPost.category }}
          </el-tag>
        </div>
        
        <div class="detail-content">
          <div class="content-text" v-html="selectedPost.content"></div>
          <div class="content-tags">
            <el-tag
              v-for="tag in selectedPost.tags"
              :key="tag"
              size="small"
              effect="plain"
              class="content-tag"
            >
              {{ tag }}
            </el-tag>
          </div>
          
          <!-- AI评分和反馈 -->
          <div v-if="selectedPost.category === 'interview' && selectedPost.enableAIQuestion" class="ai-assessment">
            <div class="ai-score">
              <el-icon><Star /></el-icon>
              <span>AI评分：{{ selectedPost.aiScore }}分</span>
            </div>
            <div class="ai-feedback">
              <h4>AI反馈：</h4>
              <p>{{ selectedPost.aiFeedback }}</p>
            </div>
          </div>
        </div>
        
        <div class="detail-stats">
          <span><el-icon><View /></el-icon> {{ selectedPost.views }} 浏览</span>
          <span><el-icon><ChatLineRound /></el-icon> {{ selectedPost.comments }} 评论</span>
          <span><el-icon><Star /></el-icon> {{ selectedPost.likes }} 点赞</span>
        </div>
        
        <div class="detail-actions">
          <el-button type="primary" @click="likePost(selectedPost)">
            <el-icon><Star /></el-icon>
            点赞
          </el-button>
          <el-button @click="sharePost(selectedPost)">
            <el-icon><Share /></el-icon>
            分享
          </el-button>
        </div>
        
        <!-- 评论区 -->
        <div class="comments-section">
          <h3>评论 ({{ selectedPost.comments }})</h3>
          
          <!-- 发表评论 -->
          <div class="comment-input">
            <el-input
              v-model="newComment"
              type="textarea"
              :rows="3"
              placeholder="写下你的评论..."
            />
            <el-button type="primary" @click="submitComment">发表评论</el-button>
          </div>
          
          <!-- 评论列表 -->
          <div class="comments-list">
            <div v-for="comment in selectedPost.commentList" :key="comment.id" class="comment-item">
              <div class="comment-header">
                <el-avatar :size="32" :src="comment.author.avatar" />
                <div class="comment-author">
                  <span class="author-name">{{ comment.author.name }}</span>
                  <span class="comment-time">{{ comment.createTime }}</span>
                </div>
              </div>
              
              <div class="comment-content">{{ comment.content }}</div>
              
              <div class="comment-actions">
                <el-button text @click="likeComment(comment)">
                  <el-icon><Star /></el-icon>
                  {{ comment.likes }}
                </el-button>
                <el-button text @click="replyComment(comment)">
                  <el-icon><ChatLineRound /></el-icon>
                  回复
                </el-button>
              </div>
              
              <!-- 回复列表 -->
              <div v-if="comment.replies && comment.replies.length > 0" class="replies-list">
                <div v-for="reply in comment.replies" :key="reply.id" class="reply-item">
                  <div class="reply-header">
                    <el-avatar :size="24" :src="reply.author.avatar" />
                    <div class="reply-author">
                      <span class="author-name">{{ reply.author.name }}</span>
                      <span class="reply-time">{{ reply.createTime }}</span>
                    </div>
                  </div>
                  
                  <div class="reply-content">{{ reply.content }}</div>
                  
                  <div class="reply-actions">
                    <el-button text @click="likeComment(reply)">
                      <el-icon><Star /></el-icon>
                      {{ reply.likes }}
                    </el-button>
                  </div>
                </div>
              </div>
              
              <!-- 回复输入框 -->
              <div v-if="replyToComment && replyToComment.id === comment.id" class="reply-input">
                <el-input
                  v-model="replyContent"
                  type="textarea"
                  :rows="2"
                  placeholder="回复评论..."
                />
                <div class="reply-actions">
                  <el-button @click="cancelReply">取消</el-button>
                  <el-button type="primary" @click="submitReply">发表回复</el-button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { Edit, Search, View, ChatLineRound, Star, Share } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 搜索和筛选
const searchQuery = ref('')
const selectedCategory = ref('')
const sortBy = ref('latest')
const currentPage = ref(1)
const pageSize = ref(10)
const totalPosts = ref(100)

// 发帖相关
const postDialogVisible = ref(false)
const postFormRef = ref(null)
const newPost = ref({
  title: '',
  category: '',
  content: '',
  tags: [],
  interviewTime: '',
  enableAIQuestion: false,
  aiScore: null,
  aiFeedback: ''
})

// 帖子表单验证规则
const postRules = {
  title: [
    { required: true, message: '请输入帖子标题', trigger: 'blur' },
    { min: 2, max: 50, message: '标题长度在2-50个字符之间', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择帖子分类', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入帖子内容', trigger: 'blur' },
    { min: 10, message: '内容至少10个字符', trigger: 'blur' }
  ]
}

// 常用标签
const commonTags = [
  'Vue3', 'React', 'JavaScript', 'TypeScript', 'Node.js',
  'Python', 'Java', 'Go', 'Docker', 'Kubernetes',
  '微服务', '前端', '后端', '全栈', '算法',
  '数据结构', '设计模式', '性能优化', '安全', '测试'
]

// 帖子详情相关
const postDetailVisible = ref(false)
const selectedPost = ref(null)
const newComment = ref('')
const replyToComment = ref(null)
const replyContent = ref('')

// 模拟帖子数据
const posts = ref([
  {
    id: 1,
    title: 'Vue3 组合式API最佳实践',
    summary: '分享在使用Vue3组合式API过程中的一些经验和最佳实践...',
    content: '详细内容...',
    category: '技术讨论',
    tags: ['Vue3', '前端', '最佳实践'],
    author: {
      name: '张三',
      avatar: 'https://placeholder.com/40x40'
    },
    createTime: '2024-03-15 14:30',
    views: 1234,
    comments: 56,
    likes: 89,
    commentList: [
      {
        id: 1,
        content: '非常实用的分享，感谢！',
        author: {
          name: '李四',
          avatar: 'https://placeholder.com/40x40'
        },
        createTime: '2024-03-15 15:20',
        likes: 12,
        replies: [
          {
            id: 11,
            content: '确实很有帮助',
            author: {
              name: '王五',
              avatar: 'https://placeholder.com/40x40'
            },
            createTime: '2024-03-15 16:30',
            likes: 3
          }
        ]
      }
    ]
  },
  {
    id: 2,
    title: '前端开发工程师面试经验分享',
    summary: '分享一次前端开发工程师的面试经历，包括技术面试和HR面试...',
    content: '详细内容...',
    category: '面试经验',
    tags: ['前端', '面试', 'Vue3'],
    author: {
      name: '李四',
      avatar: 'https://placeholder.com/40x40'
    },
    createTime: '2024-03-16 10:30',
    interviewTime: '2024-03-15 14:00',
    views: 856,
    comments: 23,
    likes: 45,
    enableAIQuestion: true,
    aiScore: 85,
    aiFeedback: '技术基础扎实，项目经验丰富，沟通能力良好。建议在系统设计方面多加练习。',
    commentList: []
  }
])

// 计算属性：过滤后的帖子列表
const filteredPosts = computed(() => {
  let result = posts.value
  
  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    result = result.filter(post => 
      post.title.toLowerCase().includes(query) ||
      post.summary.toLowerCase().includes(query) ||
      post.tags.some(tag => tag.toLowerCase().includes(query))
    )
  }
  
  // 分类过滤
  if (selectedCategory.value) {
    result = result.filter(post => post.category === selectedCategory.value)
  }
  
  // 排序
  result = [...result].sort((a, b) => {
    switch (sortBy.value) {
      case 'latest':
        return new Date(b.createTime) - new Date(a.createTime)
      case 'most_comments':
        return b.comments - a.comments
      case 'most_likes':
        return b.likes - a.likes
      default:
        return 0
    }
  })
  
  return result
})

// 方法
const handleSearch = () => {
  currentPage.value = 1
  // 这里可以调用后端API进行搜索
}

const handleCategoryChange = () => {
  currentPage.value = 1
  // 这里可以调用后端API获取分类帖子
}

const handleSortChange = () => {
  // 这里可以调用后端API获取排序后的帖子
}

const handleSizeChange = (val) => {
  pageSize.value = val
  // 这里可以调用后端API获取新的分页数据
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  // 这里可以调用后端API获取新的分页数据
}

const getCategoryTag = (category) => {
  const types = {
    '学习经验': 'success',
    '技术讨论': 'primary',
    '问题求助': 'warning',
    '资源分享': 'info'
  }
  return types[category] || 'default'
}

const showPostDialog = () => {
  postDialogVisible.value = true
  newPost.value = {
    title: '',
    category: '',
    content: '',
    tags: [],
    interviewTime: '',
    enableAIQuestion: false,
    aiScore: null,
    aiFeedback: ''
  }
}

const submitPost = async () => {
  if (!postFormRef.value) return
  
  await postFormRef.value.validate(async (valid) => {
    if (valid) {
      if (newPost.value.category === 'interview' && newPost.value.enableAIQuestion) {
        await generateAIQuestions()
      }
      
      // 这里调用后端API提交帖子
      ElMessage.success('帖子发布成功')
      postDialogVisible.value = false
    }
  })
}

const viewPostDetail = (post) => {
  selectedPost.value = post
  postDetailVisible.value = true
  // 这里可以调用后端API获取帖子详情
}

const likePost = (post) => {
  post.likes++
  ElMessage.success('点赞成功')
}

const sharePost = (post) => {
  // 实现分享功能
  ElMessage.success('分享链接已复制到剪贴板')
}

const submitComment = () => {
  if (!newComment.value.trim()) {
    ElMessage.warning('请输入评论内容')
    return
  }
  
  if (selectedPost.value) {
    // 这里调用后端API提交评论
    selectedPost.value.comments++
    selectedPost.value.commentList.unshift({
      id: Date.now(),
      content: newComment.value,
      author: {
        name: '当前用户',
        avatar: 'https://placeholder.com/40x40'
      },
      createTime: new Date().toLocaleString(),
      likes: 0,
      replies: []
    })
    
    ElMessage.success('评论发表成功')
    newComment.value = ''
  }
}

const likeComment = (comment) => {
  comment.likes++
  ElMessage.success('点赞成功')
}

const replyComment = (comment) => {
  replyToComment.value = comment
  replyContent.value = ''
}

const cancelReply = () => {
  replyToComment.value = null
  replyContent.value = ''
}

const submitReply = () => {
  if (!replyContent.value.trim()) {
    ElMessage.warning('请输入回复内容')
    return
  }
  
  if (replyToComment.value) {
    // 这里调用后端API提交回复
    if (!replyToComment.value.replies) {
      replyToComment.value.replies = []
    }
    
    replyToComment.value.replies.push({
      id: Date.now(),
      content: replyContent.value,
      author: {
        name: '当前用户',
        avatar: 'https://placeholder.com/40x40'
      },
      createTime: new Date().toLocaleString(),
      likes: 0
    })
    
    ElMessage.success('回复发表成功')
    replyToComment.value = null
    replyContent.value = ''
  }
}

const generateAIQuestions = async () => {
  if (!newPost.value.enableAIQuestion) return
  
  try {
    // 这里调用后端API生成AI题目
    ElMessage.success('AI题目生成中...')
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 模拟AI生成的题目和评分
    newPost.value.content += '\n\nAI生成的面试题目：\n1. 请详细解释Vue3的响应式系统原理\n2. 如何优化前端性能？请列举具体方案\n3. 描述一下微前端架构的优势和实现方案'
    
    ElMessage.success('AI题目生成完成')
  } catch (error) {
    ElMessage.error('AI题目生成失败')
  }
}
</script>

<style scoped>
.learning-community {
  padding: 20px;
}

.community-header {
  text-align: center;
  margin-bottom: 30px;
}

.community-header h2 {
  margin-bottom: 10px;
  color: #303133;
}

.community-header p {
  color: #606266;
  margin-bottom: 20px;
}

.filter-section {
  display: flex;
  gap: 20px;
  margin-bottom: 30px;
}

.search-input {
  width: 300px;
}

.posts-list {
  margin-bottom: 20px;
}

.post-card {
  margin-bottom: 20px;
  transition: transform 0.3s;
}

.post-card:hover {
  transform: translateY(-5px);
}

.post-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.post-author {
  display: flex;
  align-items: center;
  gap: 10px;
}

.author-info {
  display: flex;
  flex-direction: column;
}

.author-name {
  font-weight: bold;
}

.post-time {
  font-size: 12px;
  color: #909399;
}

.post-content {
  cursor: pointer;
}

.post-title {
  margin: 0 0 10px 0;
  font-size: 18px;
  color: #303133;
}

.post-summary {
  color: #606266;
  margin-bottom: 10px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.post-tags {
  margin: 10px 0;
}

.post-tag {
  margin-right: 5px;
}

.post-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #ebeef5;
}

.post-stats {
  display: flex;
  gap: 15px;
  color: #909399;
}

.post-actions {
  display: flex;
  gap: 10px;
}

.pagination-section {
  margin-top: 20px;
  text-align: center;
}

.post-detail {
  padding: 20px;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.author-meta {
  display: flex;
  flex-direction: column;
  margin-left: 10px;
}

.detail-content {
  margin: 20px 0;
}

.content-text {
  line-height: 1.6;
  color: #303133;
}

.content-tags {
  margin-top: 15px;
}

.content-tag {
  margin-right: 5px;
}

.detail-stats {
  display: flex;
  gap: 20px;
  color: #909399;
  margin: 15px 0;
}

.detail-actions {
  display: flex;
  gap: 10px;
  margin: 20px 0;
}

.comments-section {
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.comment-input {
  margin: 20px 0;
}

.comment-input .el-button {
  margin-top: 10px;
  float: right;
}

.comments-list {
  margin-top: 20px;
}

.comment-item {
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.comment-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}

.comment-author {
  display: flex;
  flex-direction: column;
}

.comment-time {
  font-size: 12px;
  color: #909399;
}

.comment-content {
  margin: 10px 0;
  color: #303133;
}

.comment-actions {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}

.replies-list {
  margin-left: 40px;
  margin-top: 10px;
  padding-left: 10px;
  border-left: 2px solid #ebeef5;
}

.reply-item {
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px dashed #ebeef5;
}

.reply-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 5px;
}

.reply-author {
  display: flex;
  flex-direction: column;
}

.reply-time {
  font-size: 12px;
  color: #909399;
}

.reply-content {
  margin: 5px 0;
  color: #606266;
}

.reply-actions {
  display: flex;
  gap: 10px;
  margin-top: 5px;
}

.reply-input {
  margin-top: 10px;
  margin-left: 40px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.reply-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 10px;
}

.ai-hint {
  margin-left: 10px;
  color: #409EFF;
  font-size: 14px;
}

.post-card .ai-score {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #67C23A;
  font-weight: bold;
}

.post-card .ai-feedback {
  margin-top: 10px;
  padding: 10px;
  background-color: #f0f9eb;
  border-radius: 4px;
  color: #67C23A;
  font-size: 14px;
}

.ai-assessment {
  margin-top: 20px;
  padding: 15px;
  background-color: #f0f9eb;
  border-radius: 4px;
}

.ai-assessment .ai-score {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #67C23A;
  font-weight: bold;
  margin-bottom: 10px;
}

.ai-assessment .ai-feedback {
  color: #67C23A;
}

.ai-assessment .ai-feedback h4 {
  margin: 0 0 10px 0;
  font-size: 16px;
}

.ai-assessment .ai-feedback p {
  margin: 0;
  line-height: 1.6;
}
</style> 